package jh.com.jhappbf.valueselect;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.utils.JsonHelper;

/**
 * @author Administrator
 */
public class ContractValueSelect extends AbActivity {
    private RelativeLayout mContentView;
    private RelativeLayout mErrorView;
    private SearchView mSearchView;
    private AbPullToRefreshView mRefreshView;
    private ListView mListView;
    private List<String> mData;
    private ArrayAdapter<String> mAdapter;
    private Button mBtnTryAgain;
    private AbLoadDialogFragment mDialogFragment = null;
    private Context mAppContext;
    private String mFlag = "";
    private String mType = "";
    private AbTitleBar mAbTitleBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.query_weight_setting_select_llistview);

        mAbTitleBar = this.getTitleBar();

        mAbTitleBar.setLogo(R.drawable.button_selector_back);
//		mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this,R.color.orange));
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));

        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        if (intent != null) {
            mFlag = intent.getStringExtra("flag");
            mType=intent.getStringExtra("mType");
        }

        switch (mFlag) {
            case "货名":
                mAbTitleBar.setTitleText("货名选择");
                break;
            case "单位":
                mAbTitleBar.setTitleText("单位选择");
                break;
            case "收货":
                mAbTitleBar.setTitleText("收货选择");
                break;
            case "发货":
                mAbTitleBar.setTitleText("发货选择");
                break;
            default:
        }

        mContentView = findViewById(R.id.query_setting_search_content);
        mErrorView = findViewById(R.id.query_setting_error_view);
        mSearchView = findViewById(R.id.query_setting_search_view);
        mRefreshView = findViewById(R.id.query_setting_select_pullToRefreshView);
        mListView = findViewById(R.id.query_setting_select_listView);
        mBtnTryAgain = findViewById(R.id.query_setting_error_btn);
        mAppContext = getApplicationContext();

        // 重试
        mBtnTryAgain.setOnClickListener(v -> loadFirst());

        // 下拉刷新
        mRefreshView.setOnHeaderRefreshListener(view -> refreshTask());

        // 上拉加载更多
        mRefreshView.setOnFooterLoadListener(view -> refreshTask());

        // 单击数据项
        mListView.setOnItemClickListener((parent, view, position, id) -> {

            TextView txt = (TextView) view;
            Intent i = new Intent();
            i.putExtra("result", txt.getText());
            setResult(0, i);
            ContractValueSelect.this.finish();
        });

        mListView.setTextFilterEnabled(true);
        mSearchView.setOnQueryTextListener(new OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (TextUtils.isEmpty(newText)) {
                    mListView.clearTextFilter();
                } else {
                    mListView.setFilterText(newText);
                }
                return true;
            }
        });
        // 设置进度条的样式
//		mRefreshView.getHeaderView().setHeaderProgressBarDrawable(ContextCompat.getDrawable(getActivity(),R.drawable.progress_circular));//过时方法
        mRefreshView.getHeaderView().setHeaderProgressBarDrawable(ContextCompat.getDrawable(this, R.drawable.progress_circular));

//		mRefreshView.getFooterView().setFooterProgressBarDrawable(ContextCompat.getDrawable(getActivity(),R.drawable.progress_circular));
        mRefreshView.getFooterView().setFooterProgressBarDrawable(ContextCompat.getDrawable(this, R.drawable.progress_circular));

        mData = new ArrayList<>();
        loadFirst();
        mAdapter = new ArrayAdapter<>(mAppContext, R.layout.list_view_item_txt, R.id.list_view_item_txt, mData);
        mListView.setAdapter(mAdapter);

    }

    /**
     * 第一次加载
     */
    private void loadFirst() {
        mDialogFragment = AbDialogUtil.showLoadDialog(ContractValueSelect.this,
                R.mipmap.ic_load, "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(() -> {
            mErrorView.setVisibility(View.GONE);
            mContentView.setVisibility(View.VISIBLE);
            refreshTask();
        });
    }

    /**
     * 下拉刷新
     */
    private void refreshTask() {
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        String methodName = "getPlanFieldValue";
        param.add("fieldName");
        param.add("type");
        switch (mFlag) {
            case "货名":
                value.add("货名");
                break;
            case "单位":
                value.add("单位");
                break;
            case "发货":
                value.add("发货");
                break;
            case "收货":
                value.add("收货");
                break;
            default:
                return;
        }
        value.add(mType);


        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(ContractValueSelect.this);
            mDialogFragment.dismiss();
            mRefreshView.onHeaderRefreshFinish();
            mRefreshView.onFooterLoadFinish();
            mErrorView.setVisibility(View.GONE);
            mContentView.setVisibility(View.VISIBLE);

            List<JSONObject> newListData = JsonHelper
                    .getJsonObjects(response);
            if (newListData != null) {
                mData.clear();
                String cargoname;
                for (int i = 0; i < newListData.size(); i++) {
                    JSONObject obj = newListData.get(i);
                    if (obj != null) {
                        cargoname = obj.optString("value");
                        if (!TextUtils.isEmpty(cargoname)) {
                            mData.add(cargoname);
                        }
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(ContractValueSelect.this);
            mDialogFragment.dismiss();
            mRefreshView.onHeaderRefreshFinish();
            mRefreshView.onFooterLoadFinish();
            mErrorView.setVisibility(View.VISIBLE);
            mContentView.setVisibility(View.GONE);
            mData.clear();
            mAdapter.notifyDataSetChanged();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }
}
